<template>
  <!-- 使用grid网格布局 指定列数为2 高度占满全屏 -->
  <div class="grid grid-cols-2 h-screen bg-white">
    <div 
      class="col-span-2 order-2 md:col-span-1 md:order-1 p-10 bg-gray-400 md:rounded-r-2xl animate__animated animate__bounceInLeft animate__fast dark:bg-gray-800">
      <!-- 指定为 flex 布局，并设置为屏幕垂直水平居中，高度为 100% 子元素垂直排列 -->
      <div class="flex justify-center items-center h-full flex-col">
        <h2 class="font-bold text-4xl mb-7 text-white">码海航行</h2>
        <p class="text-white mb-4">一款由 Spring Boot + Vue 3.2 开发的数据可视化博客系统</p>
        <p class="text-white mb-4">作者：226786078 柯华杰</p>
        <img src="@/assets/developer.png" class="w-1/2 md:rounded-2xl">
      </div>
    </div>
    <div class="flex flex-col col-span-2 order-1 md:col-span-1 md:order-2 bg-white dark:bg-gray-800 md:rounded-l-2xl">
      <ChangeTheme class=" ml-auto"></ChangeTheme>
      <div class="flex justify-center items-center h-4/5 flex-col animate__animated animate__bounceInRight animate__fast">
          <!-- 登录页面 -->
          <div v-if="index == 0" class="w-5/6 md:w-2/5">
            <!-- 大标题，设置字体粗细、大小、下边距 -->
            <h1 class="font-bold text-center text-4xl mb-5 dark:text-white">欢迎回来</h1>
            <!-- 设置 flex 布局，内容垂直水平居中，文字颜色，以及子内容水平方向 x 轴间距 -->
            <div class="flex items-center justify-center mb-7 text-gray-400 space-x-2 dark:text-gray-500">
              <!-- 左边横线，高度为 1px, 宽度为 16，背景色设置 -->
              <span class="h-[1px] w-16 bg-gray-200 dark:bg-gray-700"></span>
              <span>账号密码登录</span>
              <!-- 右边横线，高度为 1px, 宽度为 16，背景色设置 -->
              <span class="h-[1px] w-16 bg-gray-200 dark:bg-gray-700"></span>
            </div>
            <el-form :model="form" :rules="rules" ref="loginFormRef">

              <el-form-item prop="username">
                <el-input v-model="form.username" size="large" placeholder="请输入账号/邮箱" :prefix-icon="Message"
                  clearable></el-input>
              </el-form-item>

              <el-form-item prop="password">
                <el-input v-model="form.password" size="large" type="password" placeholder="请输入密码" :prefix-icon="Lock"
                  clearable show-password></el-input>
              </el-form-item>

              <el-form-item>
                <el-button class="w-full" size="large" :loading="loading" type="primary" @click="onLogin">登录</el-button>
              </el-form-item>

              <!-- 底部 -->
              <el-form-item class="flex justify-between">
                <el-link type="info" :underline="false" @click="changePage(1)">立即注册</el-link>
                <el-link type="info" class="ml-auto" :underline="false" @click="changePage(2)">忘记密码</el-link>
              </el-form-item>

            </el-form>
          </div>

          <!-- 注册页面 -->
          <div v-if="index == 1" class="w-5/6 md:w-2/5">
            <!-- 大标题，设置字体粗细、大小、下边距 -->
            <h3 class="font-bold text-center text-4xl mb-5">注册页面</h3>
            <el-form :model="form" :rules="rules" ref="registerFormRef">

              <el-form-item prop="email">
                <el-input v-model="form.email" size="large" placeholder="请输入邮箱" :prefix-icon="Message"
                  clearable></el-input>
              </el-form-item>

              <el-form-item prop="nickname">
                <el-input v-model="form.nickname" size="large" placeholder="请输入昵称" :prefix-icon="User"
                  clearable></el-input>
              </el-form-item>

              <el-form-item prop="password">
                <el-input v-model="form.password" size="large" type="password" placeholder="请输入密码" :prefix-icon="Lock"
                  clearable show-password></el-input>
              </el-form-item>

              <el-form-item class="flex" prop="code">
                <el-input v-model="form.code" style="width: 140px;" size="large" placeholder="请输入验证码" :prefix-icon="CircleCheck" clearable></el-input>
                <el-button v-if="showSendButton" class="ml-auto" :loading="codeLoading" @click="handleSendEmailCode(1)">发送验证码</el-button>
                <!-- <a v-if="showSendButton" class="hand-style ml-7 text-sky-500" @click="handleSendEmailCode">发送验证码</a>
                <a v-else class="ml-auto">{{ countdown }}秒后重新获取</a> -->
                <el-button v-else class="ml-auto">{{ countdown }}秒后重新获取</el-button>
              </el-form-item>

              <el-form-item>
                <el-button class="w-full hand-style" size="large" :loading="loading" type="primary" @click="onRegister">注册</el-button>
              </el-form-item>

              <!-- 底部 -->
              <el-form-item>
                <el-link type="info" :underline="false" @click="changePage(0)">已有账号，去登录</el-link>
              </el-form-item>

            </el-form>
          </div>

          <!-- 忘记密码 -->
          <div v-if="index == 2" class="w-5/6 md:w-2/5">
            <!-- 大标题，设置字体粗细、大小、下边距 -->
            <h3 class="font-bold text-center text-4xl mb-5">忘记密码</h3>
            <el-form :model="form" :rules="rules" ref="forgetFormRef">

              <el-form-item prop="email">
                <el-input v-model="form.email" size="large" placeholder="请输入邮箱" :prefix-icon="Message"
                  clearable></el-input>
              </el-form-item>

              <el-form-item prop="password">
                <el-input v-model="form.password" size="large" type="password" placeholder="请输入新密码" :prefix-icon="Lock"
                  clearable show-password></el-input>
              </el-form-item>

              <el-form-item class="flex" prop="code">
                <el-input v-model="form.code" style="width: 140px;" size="large" placeholder="请输入验证码" :prefix-icon="CircleCheck"
                  clearable></el-input>
                  <!-- <a v-if="showSendButton" class="hand-style ml-7 text-sky-500" @click="handleSendEmailCode">发送验证码</a> -->
                  <el-button v-if="showSendButton" class="ml-auto" :loading="codeLoading" @click="handleSendEmailCode(2)">发送验证码</el-button>
                  <!-- <a v-else class="ml-auto">{{ countdown }}秒后重新获取</a> -->
                  <el-button v-else class="ml-auto">{{ countdown }}秒后重新获取</el-button>
              </el-form-item>

              <el-form-item>
                <el-button class="w-full" size="large" :loading="loading" type="primary" @click="onForgetPassword">修改</el-button>
              </el-form-item>

              <!-- 底部 -->
              <el-form-item>
                <el-link type="info" :underline="false" @click="changePage(0)">已有账号，去登录</el-link>
              </el-form-item>

            </el-form>
          </div>
        </div>
      </div>
  </div>
</template>
<script setup>
// 引入 Element Plus 中的用户、锁图标
import { User, Lock, Message, CircleCheck } from '@element-plus/icons-vue'
import { loginService } from '@/api/admin/user'
import { reactive, ref, onMounted, onBeforeUnmount, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router';
import { showMessage } from '@/composables/util'
import { setToken } from '@/composables/cookie'
import { useUserStore } from '@/stores/user'
import { registerService, sendEmailCode, forgetPasswordService } from '@/api/admin/common'
import ChangeTheme from '@/components/ChangeTheme.vue'

const route = useRoute()

const userStore = useUserStore()

const router = useRouter()

const loading = ref(false)

const codeLoading = ref(false)

// index用来v-if切换页面  0: 登录  1: 注册  2: 忘记密码
const index = ref(0)

// 定义响应式的表单对象
const form = reactive({
  email: '',
  username: '',
  password: '',
  nickname: '',
  code: '',
})

// 登录表单引用
const loginFormRef = ref(null)
// 注册表单引用
const registerFormRef = ref(null)
// 忘记密码表单引用
const forgetFormRef = ref(null)

// 表单验证规则
const rules = {
  email: [
    {
      required: true,
      message: '邮箱不能为空',
      trigger: 'blur',
    },
  ],
  username: [
    {
      required: true,
      message: '账号/邮箱不能为空',
      trigger: 'blur'
    },
  ],
  password: [
    {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    },
  ],
  nickname: [
    {
      required: true,
      message: '昵称不能为空',
      trigger: 'blur'
    },
  ],
  code: [
    {
      required: true,
      message: '验证码不能为空',
      trigger: 'blur'
    },
  ],
}

// 登录
const onLogin = async () => {
  // 登录前先校验表单
  await loginFormRef.value.validate()
  // 加入loading加载
  loading.value = true
  const res = await loginService(form.username, form.password)
  // 请求完毕后结束loading加载
  loading.value = false
  console.log(res)
  if (res.success == true) {
    const token = res.data.token
    setToken(token)
    // 获取用户信息，并存储到全局状态
    userStore.setUserInfo()
    showMessage('登录成功')
    router.push('/')

  } else {
    // 获取服务端返回的错误消息
    const message = res.message
    showMessage(message, 'error')
  }
}

// 按回车键后，执行登录事件
function onKeyUp(e) {
  console.log(e)
  if (e.key == 'Enter') {
    onLogin()
  }
}

// 网页组件渲染后 添加键盘监听
onMounted(() => {
  document.addEventListener('keyup', onKeyUp)
})

// 移除键盘监听
onBeforeUnmount(() => {
  document.removeEventListener('keyup', onKeyUp)
})


// 是否展示发送按钮
const showSendButton = ref(true)
// 倒计时初始化为 60 秒
const countdown = ref(60)


// 点击 立即注册 跳转注册页面
const changeRegisterPage = () => {
  // 跳转注册页面
  index.value = 1
  // 清空表单数据
  form.email = ''
  form.username = ''
  form.password = ''
  form.nickname = ''
  form.code = ''
 }

const changePage = (n) => {
  // 清空表单数据
  form.email = ''
  form.username = ''
  form.password = ''
  form.nickname = ''
  form.code = ''
  if (n == 1) {
    // 跳转注册页面
    index.value = 1
  } else if (n == 2) {
    // 跳转忘记密码页面
    index.value = 2
  } else {
    // 跳转登录页面
    index.value = 0
  }
}

// ===============注册页面=======================

// 倒计时定时器
let timer = null

// 发送验证码按钮
const handleSendEmailCode = async (type) => {

  // 验证邮箱是否正确
  if (form.email == '') {
    showMessage('请输入邮箱', 'error')
    return
  }
  // 验证邮箱格式是否正确
  if (!form.email.match(/^[A-Za-z0-9]+([-._][A-Za-z0-9]+)*@[A-Za-z0-9]+(-[A-Za-z0-9]+)*(\.[A-Za-z]{2,6}|[A-Za-z]{2,4}\.[A-Za-z]{2,3})$/)) {
    showMessage('请输入正确的邮箱', 'error')
    return
  }
  // 加入loading加载
  codeLoading.value = true
  // 发送获取验证码请求   type类型  1 注册  2 忘记密码
  sendEmailCode(form.email, type).then(res => {
    if (res.success) {
      showMessage('验证码发送成功', 'success')
      // 关闭loading加载
      codeLoading.value = false
      showSendButton.value = false
      // 开启倒计时
      timer = setInterval(() => {
        countdown.value--
        if (countdown.value == 0) {
          // 倒计时结束，显示发送按钮
          showSendButton.value = true
          // 清除定时器
          clearInterval(timer)
          // 重置倒计时
          countdown.value = 60
        }
      }, 1000)
    } else {
      // 关闭loading加载
      codeLoading.value = false
      showMessage(res.message, 'error')
    }
  }).catch(error => {
    // 关闭loading加载
    codeLoading.value = false
    showMessage(res.message, 'error')
  })
  
  

  // const res = await sendEmailCode(form.email, type)
  // 关闭loading加载
  // codeLoading.value = false
  // if (res.success) {
    // 发送成功后，隐藏发送按钮
  //   showSendButton.value = false
    
  //   // 开启倒计时
  //   timer = setInterval(() => {
  //     countdown.value--
  //     if (countdown.value == 0) {
  //       // 倒计时结束，显示发送按钮
  //       showSendButton.value = true
  //       // 清除定时器
  //       clearInterval(timer)
  //       // 重置倒计时
  //       countdown.value = 60
  //     }
  //   }, 1000)
  // } else {
  //   // 关闭loading加载
  //   codeLoading.value = false
  //   showMessage(res.message, 'error')
  // }

}


// 注册
const onRegister = async () => {
    // 注册前先校验表单
    await registerFormRef.value.validate()
    // 加入loading加载
    loading.value = true
    // 发送注册请求
    const res = await registerService({
      email: form.email, 
      password: form.password, 
      nickname: form.nickname, 
      code: form.code
    })
    if (res.success) {
      // 关闭loading加载
      loading.value = false
      showMessage('注册成功', 'success')
      // 清除定时器
      clearInterval(timer)
      showSendButton.value = true
      // 切换到登录页面
      changePage(0)
    } else {
      showMessage(res.message, 'error')
      // 关闭loading加载
      loading.value = false
    }

}

// 忘记密码-修改密码
const onForgetPassword = async () => {
    // 注册前先校验表单
    await forgetFormRef.value.validate()
    // 加入loading加载
    loading.value = true
    const res = await forgetPasswordService({
      email: form.email,
      password: form.password,
      code: form.code
    })
    if (res.success) {
      // 关闭loading加载
      loading.value = false
      showMessage('修改成功', 'success')
      // 清除定时器
      clearInterval(timer)
      showSendButton.value = true
      // 切换到登录页面
      changePage(0)
    } else {
      showMessage(res.message, 'error')
      // 关闭loading加载
      loading.value = false
    }
}



</script>